package com.upcode.weighing.common.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.util.concurrent.TimeUnit;

public class SequenceUtils {
    /**
     * 自增序列,初始值为1
     * @param redisTemplate
     * @param key
     * @param expireTime         过期时间,单位秒
     * @return
     */
    public static long incv(RedisTemplate redisTemplate, String key, long expireTime){
        return incv(redisTemplate,key,1,expireTime);
    }

    /**
     * 自增序列
     * @param redisTemplate
     * @param key
     * @param initialValue      初始值
     * @param expireTime        过期时间,单位秒
     * @return
     */
    public static long incv(RedisTemplate redisTemplate,String key,long initialValue,long expireTime){
        return incv(redisTemplate,key,initialValue,expireTime, TimeUnit.SECONDS);
    }

    /**
     *
     * @param redisTemplate
     * @param key
     * @param initialValue      初始值
     * @param expireTime        过期时间
     * @param timeUnit          过期时间单位
     * @return
     */
    public static long incv(RedisTemplate redisTemplate,String key,Long initialValue,long expireTime, TimeUnit timeUnit){
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = null;
        if(entityIdCounter != null) {
        	increment = entityIdCounter.getAndIncrement();
        }
        if ((null == increment || increment.longValue() == 0) && expireTime > 0) {//初始设置过期时间
            entityIdCounter.expire(expireTime, timeUnit);//单位毫秒
        }
        
        if(increment == null) {
        	return initialValue;
        }
        
        return increment+initialValue;
    }
}
